import { ProColumns, ProTable } from '@/components/Pro';
import { realTimeMonitoringControllerAreaOverview as overviewsList } from '@/services/ess/realTimeMonitoring';
import { stationAreaControllerImplListStationArea as areaList } from '@/services/ess/stationArea';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import React, { useEffect, useState } from 'react';
import { useIntl } from 'umi';
import {
  useParams,
  useSelectedDeviceNode,
  useSetSelectedDevice,
} from '../../SelectedDeviceNodeContext';
import Styles from './index.less';

interface IProps {
  showArea?: boolean;
}

interface Item {
  label: string;
  value: string | number;
  remark?: string;
}

export const SubareaOverview: React.FC<IProps> = ({ showArea }) => {
  const deviceNode = useSelectedDeviceNode();
  const setSelectedDevice1 = useSetSelectedDevice();
  const [partitions, setPartitions] = useState([]);
  const params = useParams();
  const intl = useIntl();

  const findNode = (name: string) => {
    let nodeReturn = null;
    if (params.treeData.length) {
      for (let node of params.treeData[0]?.children) {
        if (node?.title === name) {
          nodeReturn = node;
          break;
        }
      }
    }
    return nodeReturn;
  };

  const [chargeDischargeStatusOptions, setChargeDischargeStatusOptions] = useState<Item[]>([]);
  useEffect(() => {
    (async () => {
      try {
        let reslut = await areaList();
        if (reslut.success) {
          let arr = reslut.data?.map((item) => {
            return {
              value: item?.id,
              label: item?.areaName,
            };
          });
          setPartitions(arr || []);
        }
        let ChargeStatus = await fetchDictInfo(DATABASE_TYPE_ENUM.CHARGE_STATUS);
        setChargeDischargeStatusOptions(ChargeStatus || []);
      } catch (error) {}
    })();
  }, []);
  const columns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
      search: false,
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.area' }),
      dataIndex: 'areaId',
      render: (_, record) => (
        <a
          onClick={() => {
            let node = findNode(record?.name);
            setSelectedDevice1(node);
          }}
        >
          {record.name}
        </a>
      ),
      valueType: 'select',
      // initialValue:areaOptions.map((option) => option.value),
      fieldProps: {
        // mode: 'multiple',
        maxTagCount: 'responsive',
        options: partitions,
      },
      hideInSearch: !showArea,
      hideInTable: !showArea,
    },
    {
      title: intl.formatMessage({ id: 'stationRealtimeMonitoring.chargeState' }),
      dataIndex: 'chargeState',
      valueType: 'select',
      // initialValue: chargeDischargeStatusOptions.map((option) => option.value),
      fieldProps: {
        // mode: 'multiple',
        maxTagCount: 'responsive',
        options: chargeDischargeStatusOptions,
      },
      render: (_, record) => {
        let arr = chargeDischargeStatusOptions.filter(
          (res) => Number(res?.value) === Number(record?.chargeStatus),
        );
        return arr[0]?.label || '--';
      },
    },
    {
      title: 'SOC(%)',
      dataIndex: 'soc',
      valueType: 'digit',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalSPower' })}`,
      dataIndex: 'totalPower',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.powerOfPoC' })}`,
      dataIndex: 'pocPower',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.loadPower' })}`,
      dataIndex: 'loadPower',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalRevenues' })}`,
      dataIndex: 'income',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.dayRevenue' })}`,
      dataIndex: 'dailyIncome',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.dayCharge' })}`,
      dataIndex: 'dailyChargeElectricity',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.dayDischarge' })}`,
      dataIndex: 'dailyDisChargeElectricity',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalCharge' })}`,
      dataIndex: 'chargedEnergy',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalDischarge' })}`,
      dataIndex: 'disChargedEnergy',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'data.dailyOnGridEnergy' })}`,
      dataIndex: 'dailyPocOnGridEnergy',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'data.dailyOffGridEnergy' })}`,
      dataIndex: 'dailyPocOffGridEnergy',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalOnGridEnergy' })}`,
      dataIndex: 'pocOnGridEnergy',
      search: false,
    },
    {
      title: `${intl.formatMessage({ id: 'stationRealtimeMonitoring.totalOffGridEnergy' })}`, //
      dataIndex: 'pocOffGridEnergy',
      search: false,
    },
  ];

  const scroll = {
    x: 'max-content',
    y: 460,
  };

  return (
    <ProTable
      className={Styles.hideXscroll}
      params={{
        deviceCode: deviceNode?.deviceCode ?? undefined,
      }}
      request={async (values) => {
        try {
          let params = {
            deviceType: deviceNode?.deviceType ?? undefined,
            ...values,
          };

          let reslut = await overviewsList(params);
          return reslut;
        } catch (err) {
          console.log(err, '错误');
        }
      }}
      scroll={scroll}
      sticky
      columns={columns}
      rowKey="pageIndex"
      search={{
        className: 'searchPosInline',
      }}
    />
  );
};
